package com.lee.single.starter.security.filter;

import com.lee.single.starter.redis.SecurityRedisComponent;
import com.lee.single.starter.response.constant.AppConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Lee
 * @date 2020/7/27
 */
public class RedisSecurityFilter extends OncePerRequestFilter {

    @Autowired
    private SecurityRedisComponent securityRedis;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader(AppConstant.HTTP_HEADER_NAME);

        if (StringUtils.hasText(token) && !AppConstant.JS_UNDEFINED.equals(token)) {
            UserDetails userDetails = securityRedis.getForEntity(token, UserDetails.class);
            if (userDetails != null) {

                // 用户每次正常操作，将redis生存时间提高到4小时后
                securityRedis.expire(token, AppConstant.EX_TIME);

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());

                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        filterChain.doFilter(request, response);
    }
}
